import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../utils/G.dart';

import 'package:provider/provider.dart';
import '../../providers/user_provider.dart';

class AddressAdd extends StatefulWidget {
  int id = 0;
  AddressAdd({Key? key, int this.id = 0}) : super(key: key);

  @override
  _AddressAddState createState() => _AddressAddState();
}

class _AddressAddState extends State<AddressAdd> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _realName = ''; // 收货人名称
  String _phone = ''; // 手机号
  Map _address = {}; // 包含四个字段 province,city,district 和 city_id
  String _detail = ""; // 详细地址
  int _isDefault = 0; // 是否为默认地址

  List _cityList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    G.api.address.cityList().then((value) {
      if (value['status'] == 200) {
        setState(() {
          print('获取省市县数据成功');
          _cityList = value['data'];
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('新增收获地址'),
          centerTitle: true,
        ),
        body: Container(
            margin: const EdgeInsets.all(10), child: _renderLoginForm()));
  }

  Widget _renderLoginForm() {
    return Form(
        key: _formKey,
        child: Column(
          children: [
            TextFormField(
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.person),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '收货人'),
                validator: (value) {
                  if (value.toString().length <= 2) {
                    return '用户名最短是两位';
                  }
                  return null;
                },
                onChanged: (value) {
                  _realName = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            TextFormField(
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.phone),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '手机号'),
                validator: (value) {
                  RegExp reg = new RegExp(r'^\d{11}$');
                  if (!reg.hasMatch(value!)) {
                    return '手机号非法';
                  }
                  return null;
                },
                onChanged: (value) {
                  _phone = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            TextFormField(
              readOnly: true,
              decoration: InputDecoration(
                  prefixIcon: const Icon(Icons.person),
                  fillColor: Colors.deepPurple.shade100,
                  filled: true,
                  border: InputBorder.none,
                  hintText: _address['geoString'] != null
                      ? _address['geoString'].toString()
                      : '选择省市县',
                  suffixIcon: TextButton(
                      onPressed: () {
                        showGeoSelection(context);
                      },
                      child: const Icon(Icons.room_outlined))),
            ),
            const SizedBox(
              height: 10,
            ),
            TextFormField(
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.details),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '详细地址'),
                validator: (value) {
                  if (value.toString().length <= 2) {
                    return '最短是两位';
                  }
                  return null;
                },
                onChanged: (value) {
                  _detail = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            CheckboxListTile(
                value: _isDefault == 1 ? true : false,
                onChanged: (value) {
                  setState(() {
                    _isDefault = value == true ? 1 : 0;
                  });
                },
                title: const Text('设置为默认地址')),
            const SizedBox(
              height: 10,
            ),
            Row(
              children: [
                Expanded(
                    child: ElevatedButton(
                        onPressed: () async {
                          if (_formKey.currentState?.validate() as bool) {
                            if (_address['geoString'] == null) {
                              G.error('请选择省市县');
                              return;
                            }

                            // 校验当前用户的登陆状态
                            if (Provider.of<UserProvider>(context,
                                    listen: false)
                                .isLogin) {
                              var tmp = _address['geoString'].split(',');
                              var geo = {
                                'province': tmp[0],
                                'city': tmp[1],
                                'district': tmp[2],
                                'city_id': _address['cityId'],
                              };

                              var res = await G.api.address.add(
                                  realName: _realName,
                                  phone: _phone,
                                  address: geo,
                                  detail: _detail,
                                  isDefault: _isDefault,
                                  id: widget.id);
                              if (res != false && res['status'] == 200) {
                                Future.delayed(
                                    const Duration(milliseconds: 500), () {
                                  G.router.navigateTo(context, '/address');
                                });
                              } else {
                                G.error('添加失败');
                              }
                            }
                          }
                        },
                        child: const Text('添加'),
                        style: ButtonStyle(
                            padding: MaterialStateProperty.all(
                                const EdgeInsets.all(12)))))
              ],
            ),
          ],
        ));
  }

  // 设置选中的省市县数据
  void handleGeoSelect(Map geoResult) {
    setState(() {
      _address = geoResult;
    });
  }

  void showGeoSelection(context) {
    showModalBottomSheet(
        context: context,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        )),
        builder: (BuildContext context) {
          return Container(
            height: 400,
            child: GeoSelection(
              onSelect: handleGeoSelect,
              geoData: _cityList,
              initProvinceIndex: _address['provinceIndex'] ?? 0,
              initCityIndex: _address['cityIndex'] ?? 0,
              initDistrictIndex: _address['districtIndex'] ?? 0,
            ),
          );
        });
  }
}

class GeoSelection extends StatefulWidget {
  final Function onSelect; // 选中函数
  final List geoData; // 初始的地理数据
  final int initProvinceIndex;
  final int initCityIndex;
  final int initDistrictIndex;

  const GeoSelection(
      {Key? key,
      required this.onSelect,
      required this.geoData,
      this.initProvinceIndex = 0,
      this.initCityIndex = 0,
      this.initDistrictIndex = 0})
      : super(key: key);

  @override
  _GeoSelectionState createState() => _GeoSelectionState();
}

class _GeoSelectionState extends State<GeoSelection> {
  List provinces = [];
  List cities = [];
  List districts = [];

  int selectedProvince = 0;
  int selectedCity = 0;
  int selectedDistrict = 0;

  /// 省份下拉框的控制器
  late FixedExtentScrollController provinceController;

  /// 城市下拉框的控制器
  late FixedExtentScrollController cityController;

  /// 区县下拉框的控制器
  late FixedExtentScrollController districtController;

  // 选中的数据
  Map tempAreaInfo = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    selectedProvince = widget.initProvinceIndex;
    selectedCity = widget.initCityIndex;
    selectedDistrict = widget.initDistrictIndex;

    provinces = widget.geoData;
    cities = provinces[selectedProvince]['c'];
    districts = cities[selectedCity]['c'];

    provinceController =
        FixedExtentScrollController(initialItem: widget.initProvinceIndex);
    cityController =
        FixedExtentScrollController(initialItem: widget.initCityIndex);
    districtController =
        FixedExtentScrollController(initialItem: widget.initDistrictIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                    child: const Text('取消'),
                    onTap: () {
                      Navigator.of(context).pop();
                    }),
                GestureDetector(
                    child: const Text('确定'),
                    onTap: () {
                      // 将选中的数据提交给父组件
                      widget.onSelect(tempAreaInfo);
                      Navigator.of(context).pop();
                    })
              ],
            ),
          ),
          Expanded(
              child: Row(
            children: [
              // 省份下拉框
              Expanded(
                  flex: 1,
                  child: CupertinoPicker(
                      scrollController: provinceController,
                      itemExtent: 48.0,
                      onSelectedItemChanged: (index) {
                        // ...
                        setState(() {
                          selectedProvince = index;
                          cities = provinces[selectedProvince]['c'];
                          selectedCity = 0;
                          districts = cities[selectedCity]['c'];
                        });
                        cityController.jumpToItem(0);
                        districtController.jumpToItem(0);
                        passParams();
                      },
                      children: _renderGeoItem(provinces))),
              // 城市下拉框
              Expanded(
                  flex: 1,
                  child: CupertinoPicker(
                      scrollController: cityController,
                      itemExtent: 48.0,
                      onSelectedItemChanged: (index) {
                        // ...
                        setState(() {
                          selectedCity = index;
                          selectedDistrict = 0;
                          districts = cities[selectedCity]['c'];
                        });
                        districtController.jumpToItem(0);
                        passParams();
                      },
                      children: _renderGeoItem(cities))),
              // 区县下拉框
              Expanded(
                  flex: 1,
                  child: CupertinoPicker(
                      scrollController: districtController,
                      itemExtent: 48.0,
                      onSelectedItemChanged: (index) {
                        // ...
                        selectedDistrict = index;
                        passParams();
                      },
                      children: _renderGeoItem(districts)))
            ],
          ))
        ],
      ),
    );
  }

  List<Widget> _renderGeoItem(List data) {
    List<Widget> target = [];
    for (var item in data) {
      target.add(Container(
        padding: const EdgeInsets.only(top: 14, bottom: 10),
        child: Text(
          item['n'] ?? '',
          style: const TextStyle(fontSize: 14),
        ),
      ));
    }

    return target;
  }

  void passParams() {
    setState(() {
      tempAreaInfo = {
        // 数据库中的 id
        'provinceId': provinces[selectedProvince]['v'],
        'cityId': cities[selectedCity]['v'],
        'districtId': districts[selectedDistrict]['v'],

        // 地理位置名称
        'geoString': provinces[selectedProvince]['n'] +
            "," +
            cities[selectedCity]['n'] +
            "," +
            districts[selectedDistrict]['n'],

        // 选中的索引值
        'provinceIndex': selectedProvince,
        'cityIndex': selectedCity,
        'districtIndex': selectedDistrict
      };
    });
  }
}
